import os  # 对系统的命令、路径等内容进行操作
import json # 使用json存取数据
from dao import *
import sys, time

current_user = ""

# 定义数据存放位置
ROOT_DIR = os.path.join(os.path.abspath("."), "database") # 我要将数据存放到代码的当前目录下
# 定义用户信息文件
USER_INFO_FILE = os.path.join(ROOT_DIR, "users.json")
ADMIN_INFO_FILE = os.path.join(ROOT_DIR, "admin.json")
BOOK_INFO_FILE = os.path.join(ROOT_DIR, "books.json")

def init():
    if not os.path.exists(ADMIN_INFO_FILE):
        os.mkdir(ROOT_DIR)
        with open(USER_INFO_FILE, mode="w") as f:
            json.dump([], f)
        with open(ADMIN_INFO_FILE, mode="w") as f:
            json.dump({"username": "admin", "password": "admin"}, f)
        with open(BOOK_INFO_FILE, mode="w") as f:
            json.dump([], f)

# =============================管理员部分==========================================
admin_bar = '''
1、登录
2、图书上架
3、用户管理
q、退出
'''

## 图书上架
def inBooks():
    book_id = input("请输入图书ID：")
    book_name = input("请输入图书名称：")
    data = read_data(BOOK_INFO_FILE) # 读取当前已有的图书列表
    for i in data:
        if i["图书ID"] == book_id:
            print("当前图书已上架")
            return
    data.append({"图书ID": book_id, "图书名称": book_name, "状态": "就绪"})
    write_data(BOOK_INFO_FILE, data)
    print("图书上架成功")

## 用户管理
def userUpdate():
    pass

# ============================用户部分===================================
user_bar = '''
1、我的信息
2、我的图书
3、借阅图书
4、归还图书
5、登录
6、注册
7、退出
'''

## 登录检查装饰器
def login_required(func):
    def wapper(*args,**kwargs):
        global current_user
        if not current_user:
            print("=========================")
            print("检测到未登录，请先登录")
            print("=========================")
            if not login():
                print("登录失败")
                return

        return func()
    return wapper

## 注册
def register():
    username = input("请输入用户名：")
    users = read_data(USER_INFO_FILE)
    if users:
        for i in users: # 如果某个值为真，则表示用户存在
            if i["用户名"] == username:
                print("当前用户已存在")
                return
    passwd = input("请输入密码：")
    users.append({"用户名": username, "密码": passwd, "图书列表": []})
    write_data(USER_INFO_FILE, users)
    print(f"用户{username}注册成功")

## 登录
def login():
    global current_user
    login_user = input("请输入用户名：")
    login_passwd = input("请输入密码：")
    users = read_data(USER_INFO_FILE)
    user = [u for u in users if u["用户名"] == login_user and u["密码"] == login_passwd]
    if user:
        print("登录成功")
        current_user = user[0]
        return True
    else:
        print("用户不存在或密码错误")


## 图书列表
def bookList():
    books = read_data(BOOK_INFO_FILE)
    if books:
        for book in books:
            if book["状态"] == "就绪":
                print(f"{book['图书ID']}-{book['图书名称']}\t可借")
            else:
                print(f"{book['图书ID']}-{book['图书名称']}\t已借出")
        
@login_required
## 图书借阅
def userBookTo():
    books = read_data(BOOK_INFO_FILE)
    book_id = input('请输入图书ID: ')
    for b in books:
        if b["图书ID"] == book_id and b["状态"] == "就绪":
            b["状态"] = "已借出"
            write_data(BOOK_INFO_FILE, books)
            users = read_data(USER_INFO_FILE)
            for i in users:
                if i['用户名'] == current_user["用户名"]:
                    i["图书列表"].append(book_id)
                    write_data(USER_INFO_FILE, users)
                    print("图书借阅成功")

@login_required
## 我的图书
def mybookList():
    for i in current_user["图书列表"]:
        print(i)

@login_required
## 图书归还
def userBookBack():
    users = read_data(USER_INFO_FILE)
    books = read_data(BOOK_INFO_FILE)
    mybookList()
    book_id = input("输入归还的图书ID")
    if book_id in current_user["图书列表"]:
        for i in users:
            if i['用户名'] == current_user["用户名"]:
                i["图书列表"].remove(book_id)
                write_data(USER_INFO_FILE,users)
                for book in books:
                    if book["图书ID"] == book_id:
                        book["状态"] = "就绪"
                        write_data(BOOK_INFO_FILE,books)
                        print("图书归还成功") 

if __name__ == "__main__": # 再这个if下面的代码只有直接调用才会执行
    init()
    if sys.argv[1] == "admin":
        while True:
            time.sleep(2)
            os.system("clear") # windows中时cls
            print(admin_bar)
            admin_info =  read_data(ADMIN_INFO_FILE)
            admin_result = input("请输入要执行的操作：")
            if admin_result == "1":
                user = input("请输入管理员账号：")
                passwd = input("请输入管理员密码：")
                if user == admin_info["username"] and passwd == admin_info["password"]:
                    print("登录成功")
            elif admin_result == "2":
                inBooks()
            elif admin_result == "3":
                print("正在开发中")
            elif admin_result == "q":
                break
    elif sys.argv[1] == "user":
        while True:
            time.sleep(1)
            os.system("clear")
            print(user_bar)
            user_result = input("请输入要执行的操作：")
            if user_result == "1":
                print("正在开发中")
            elif user_result == "2":
                mybookList()
            elif user_result == "3":
                bookList()
                userBookTo()
            elif user_result == "4":
                userBookBack()
            elif user_result == "5":
                login()
            elif user_result == "6":
                register()
            elif user_result == "7":
                break